﻿using System.Diagnostics;
using UnityEngine;
using WorldMapBase;
using Yoozoo.Gameplay.RTS;
using Yoozoo.Gameplay.RTS.Proto;

public class TruckAttackerBehaviour
{
    public Vector3 position;
    public Vector3 forward;
    private MarchEntity targetTruck;
    private float truckAccelerateValue;
    private float truckTargetSpeed;
    private float truckCurrentSpeed;
    private int truckAttackerState;
    private float parallelTime = 2;
    private float stateStartTime;
    private MarchEntity march;

    private bool isAttackerWin;
    private bool isWin;

    private float knockBackStartTime;
    private float accelerateTime = 2f;

    private int _battleIdx = 1;
    private float delayTime = 0f;

    private string battleRes = "";
    private bool bShowRes = false;
    // isAttackerWin代表单场胜利
    // isWin代表最终胜利
    public void Start(MarchEntity targetTruck,MarchEntity selfMarch,bool isAttackerWin,bool isWin,int battleIdx,string res,float delayTime)
    {
        battleRes = res;
        bShowRes = false;
        truckAttackerState = 1;
        this.isWin = isWin;
        _battleIdx = battleIdx;
        this.targetTruck = targetTruck;
        stateStartTime = Time.time;
        march = selfMarch;
        this.isAttackerWin = isAttackerWin;

        if (delayTime > 0)
        {

            truckAttackerState = 0;
            this.delayTime = delayTime;
        }
        else
        {
            SetStartPostion();
        }

        if (battleIdx == 1)
        {
            FlyTextManager.Play(FlyTextManager.GrabTruckBattle, targetTruck.Position, "BATTLE", 1);
        }
    }

    private void SetStartPostion()
    {
        //第一阶段，从远处加速，持续时间1秒
        truckTargetSpeed = targetTruck.RtsServerInfo.speed / 3600;
        truckCurrentSpeed = truckTargetSpeed * 20;
        truckAccelerateValue = (truckCurrentSpeed - truckTargetSpeed) / accelerateTime;
        var distance = (truckCurrentSpeed * truckCurrentSpeed - truckTargetSpeed * truckTargetSpeed) / (2 * truckAccelerateValue) - accelerateTime * truckTargetSpeed;
        var direction = targetTruck.Forward;
        var startPosition = targetTruck.Position - direction * distance;
        startPosition = GetTargetPosition(startPosition);
        position = startPosition;
        forward = direction;
    }

    public void Update()
    {
        var deltaTime = Time.deltaTime;
        var time = Time.time;
        if (truckAttackerState == 0)
        {

            if (time - stateStartTime >= delayTime)
            {
                truckAttackerState = 1;
                stateStartTime = Time.time;
                SetStartPostion();
            }
        }
        else if (truckAttackerState == 1)
        {
            //匀减速追赶目标的位置
            var accelerate = truckAccelerateValue * deltaTime;
            truckCurrentSpeed -= accelerate;
            truckCurrentSpeed = Mathf.Max(truckCurrentSpeed, truckTargetSpeed);
            var isArrived = TraceTarget(deltaTime);
            if (isArrived || time - stateStartTime >= accelerateTime)
            {
                truckAttackerState = 2;
                stateStartTime = Time.time;
            }
        }
        else if (truckAttackerState == 2)
        {
            targetTruck.MarchInfo.SetIsClientInBattle(!targetTruck.RtsServerInfo.isNullTroop);
            march.MarchInfo.SetIsClientInBattle(true);
            //并行
            TraceTarget(deltaTime);
            //需要处理失败方抛飞
            if (time - knockBackStartTime > 0.8f)
            {
                knockBackStartTime = time;
            }
            if (time - stateStartTime >= parallelTime)
            {
                truckAttackerState = 3;
                stateStartTime = Time.time;
                if (isAttackerWin)
                {
                    targetTruck.Hud.ShowSkillHitEffect();
                    if (targetTruck.isTrainDefenceMarch())
                    {
                        targetTruck.MarchInfo.SetServerMarchTypeAndStatus(MarchStatus.REMOVE_4, MarchType.DIE_5);
                        targetTruck.Hud?.OnUpdateMarchTypeAndStatus();
                    }
                }
                else
                {
                    march.Hud.ShowSkillHitEffect();
                    if (march.isTrainAttackerMarch())
                    {
                        march.MarchInfo.SetServerMarchTypeAndStatus(MarchStatus.REMOVE_4, MarchType.DIE_5);
                        march.Hud?.OnUpdateMarchTypeAndStatus();
                    }
                }
           
               
            }
        }
        else if (truckAttackerState == 3)
        {
            //加速远离
            var accelerate = truckAccelerateValue * deltaTime;
            truckCurrentSpeed += accelerate;
            var speedThisFrame = truckCurrentSpeed * deltaTime;
            position += forward * speedThisFrame;
            if (time - stateStartTime > 5)
            {
                truckAttackerState = -1;
            }
            else if (time - stateStartTime > 3)
            {
                march.ReadyToHide();
                if (targetTruck.isTrainDefenceMarch())
                {
                    targetTruck.ReadyToHide();
                }
                //胜利失败飘字
                if (_battleIdx == 1 && !bShowRes)
                {
                    bShowRes = true;
                    if (string.IsNullOrEmpty(battleRes))
                    {
                        if (isWin)
                        {
                            FlyTextManager.Play(FlyTextManager.GrabTruckVictory, targetTruck.Position, "VICTORY", 1);
                        }
                        else
                        {
                            FlyTextManager.Play(FlyTextManager.GrabTruckDefeat, targetTruck.Position, "DEFEAT", 1);
                        }
                    }
                    else
                    {
                        if (isWin)
                        {
                            FlyTextManager.Play(FlyTextManager.GrabTrainVictory, targetTruck.Position, "VICTORY," + battleRes, 1);
                        }
                        else
                        {
                            FlyTextManager.Play(FlyTextManager.GrabTrainDefeat, targetTruck.Position, "DEFEAT," + battleRes, 1);
                        }

                    }
                }
            }
            else if (time - stateStartTime > 1)
            {
                var attackTarget = targetTruck;
                if (attackTarget != null)
                {
                    var marchInfo = attackTarget.MarchInfo;
                    marchInfo.SetIsInBattle(false);
                    marchInfo.SetIsClientInBattle(false);
                    marchInfo.SetIsJustLeaveBattle(true);
                    attackTarget.SetIsTrainFighting(false);
                    var hud = ((MarchHud)attackTarget.Hud);
                    if (hud != null)
                    {
                        hud.SetIsInBattle(false);
                        hud.SetIsTruckFighting(false);
                        hud.SetIsTrainFighting(false);
                    }
                }

                var m = march.MarchInfo;
                m.SetIsInBattle(false);
                m.SetIsClientInBattle(false);
                m.SetIsJustLeaveBattle(true);
                march.SetIsTrainFighting(false);
                var h = ((MarchHud)march.Hud);
                if (h != null)
                {
                    h.SetIsInBattle(false);
                    h.SetIsTruckFighting(false);
                    h.SetIsTrainFighting(false);
                }
                march.FadeOut(1);
            }
        }
    }
    
    private bool TraceTarget(float deltaTime)
    {
        var targetPosition = GetTargetPosition(targetTruck.Position);
        var speedThisFrame = truckCurrentSpeed * deltaTime;
        if (Vector3.Distance(targetPosition,position) <= speedThisFrame)
        {
            position = targetPosition;
            forward = targetTruck.Forward;
            return true;
        }
        else
        {
            var direction = (targetPosition - position).normalized;
            position += direction * speedThisFrame;
            forward = direction;
            return false;
        }
    }

    private Vector3 GetTargetPosition(Vector3 startPosition)
    {
        var forward = targetTruck.Forward;
        float offset_L = _battleIdx == 1 ? 1f : 0.7f;
        var targetPosition = startPosition + Quaternion.AngleAxis(-90, Vector3.up) * forward * offset_L;
        return targetPosition;
    }

    public bool IsAttacking()
    {
        return truckAttackerState != 0;
    }

    public Vector3 getPosition()
    {
        if (truckAttackerState == 0)
        {
            return GlobalValue.INVISIBLE_POSITION;
        }
        else
        {
            return position;
        }
    }
}